﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TextLine : MonoBehaviour
{
    public TextMesh textMesh;
    public UISprite uISprite;
    private Renderer renderer;
    private string lastText = "";

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (textMesh != null)
        {
            if (renderer == null)
            {
                renderer = textMesh.GetComponent<Renderer>();
            }
            if (lastText != textMesh.text)
            {
                UpdateTextLine();
            }
        }
        else
        {
            textMesh = base.gameObject.GetComponentInChildren<TextMesh>();
        }
    }

    public void UpdateTextLine()
    {

        float x = renderer.bounds.size.x / renderer.transform.lossyScale.x;
        if (x > uISprite.width)
        {
            float proportions = uISprite.width / x;
            int lineLenght = (int)(textMesh.text.Length * proportions);
            if (lineLenght > textMesh.text.Length)
            {
                return;
            }
            string text = textMesh.text.Substring(0, lineLenght) + "\n" + textMesh.text.Substring(lineLenght, textMesh.text.Length - lineLenght);
            textMesh.text = text;
            lastText = text;
        }
        if (renderer.sharedMaterial.renderQueue == 3000) renderer.sharedMaterial.renderQueue += 1;
    }
}
